import { useReactive } from "ahooks";
import { useModel } from "umi";
import compress from "gql-compress";
import { useEffect } from "react";

import personFemale from "../../assets/images/person_female.png";
import personMale from "../../assets/images/person_male.png";

const useInstitutionDepartmentsWithMembers = (oiRoot, oiType) => {
    const { graphqlFetch } = useModel("global");

    const state = useReactive({
        loading: false,
        departments: [],
    });

    const loadInstitutionDepartmentsWithMembers = async () => {
        state.loading = true;
        let res = await graphqlFetch({
            query,
            variables: {
                oiType,
                oiRoot,
            },
        });
        let departments =
            res?.a?.nodes.map((item, i) => {
                return {
                    ...item,
                    id: oiRoot + "-dp-" + i,
                    type: "职能部门",
                    members: item.members.nodes.map((item) => ({
                        id: item.reUuid,
                        reUuid: item.reUuid,
                        reType: item.reType,
                        oimRemk: item.oimRemk,
                        oiUuid: item.oiUuid,
                        ...item.member,
                        value: {
                            name: item.member.omPosi,
                            title: item.member.omName,
                            type: "机构成员",
                            icon: item.member?.omAvta ? kuboUrl + item.member.omAvta : item.member.omRoge === "男" ? personMale : personFemale,
                        },
                    })),
                };
            }) || [];
        state.departments = departments;
        state.loading = false;
        return departments;
    };

    useEffect(() => {
        oiRoot && loadInstitutionDepartmentsWithMembers();
    }, [oiRoot]);

    return { ...state, loadInstitutionDepartmentsWithMembers };
};

const query = compress(`query MyQuery($oiType: String!, $oiRoot: UUID!) {
    a: allOrganizationInstitutions(condition: { oiType: $oiType, oiRoot: $oiRoot }, orderBy: PY_NAME_ASC) {
        nodes {
            oiName
            asInfo
            maInfo
            oiPaid
            oiType
            oiUuid
            oiDesc
            crInfo
            members: organizationInstitutionsMembersByOiUuid {
                nodes {
                    reUuid
                    reType
                    oiUuid
                    oimRemk
                    member: organizationMemberByOmUuid {
                        omUuid
                        omName
                        omAvta
                        omRoge
                        omPosi
                        omEona
                        omEouu
                    }
                }
            }
        }
    }
}`);

export default useInstitutionDepartmentsWithMembers;
